// 网站信息导入工具
export const fetchWebsiteInfo = async (url) => {
    try {
        // 确保URL格式正确
        const normalizedUrl = url.startsWith('http') ? url : `https://${url}`;
        const urlObj = new URL(normalizedUrl);

        // 由于CORS限制，我们无法直接获取网页内容
        // 这里提供一个基础的实现，实际项目中可能需要后端支持
        const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(normalizedUrl)}`);
        const data = await response.json();

        if (!data.contents) {
            throw new Error('无法获取网页内容');
        }

        // 解析HTML内容
        const parser = new DOMParser();
        const doc = parser.parseFromString(data.contents, 'text/html');

        // 获取网站标题
        let title = doc.querySelector('title')?.textContent?.trim();
        if (!title) {
            title = urlObj.hostname.replace('www.', '');
        }

        // 获取favicon
        let icon = '';
        const iconSelectors = [
            'link[rel="icon"]',
            'link[rel="shortcut icon"]',
            'link[rel="apple-touch-icon"]',
            'link[rel="apple-touch-icon-precomposed"]'
        ];

        for (const selector of iconSelectors) {
            const iconElement = doc.querySelector(selector);
            if (iconElement) {
                icon = iconElement.getAttribute('href');
                break;
            }
        }

        // 处理相对路径的图标
        if (icon && !icon.startsWith('http')) {
            if (icon.startsWith('//')) {
                icon = `https:${icon}`;
            } else if (icon.startsWith('/')) {
                icon = `${urlObj.protocol}//${urlObj.host}${icon}`;
            } else {
                icon = `${urlObj.protocol}//${urlObj.host}/${icon}`;
            }
        }

        // 如果没有找到图标，使用默认的favicon路径
        if (!icon) {
            icon = `${urlObj.protocol}//${urlObj.host}/favicon.ico`;
        }

        return {
            name: title,
            url: normalizedUrl,
            icon: icon,
            searchUrl: generateSearchUrl(normalizedUrl),
            disabled: false
        };
    } catch (error) {
        console.error('获取网站信息失败:', error);
        throw error;
    }
};

// 生成网站名称的函数
const generateWebsiteName = (hostname) => {
    const nameMap = {
        'douban.com': '豆瓣电影',
        'movie.douban.com': '豆瓣电影',
        'imdb.com': 'IMDb',
        'subaibai.com': '素白白影视',
        'libvio.site': 'libvio影视',
        'ddys.pro': '低端影视',
        'gimy.ai': 'gimy剧迷',
        'anime1.me': 'Anime动漫',
        'dddym.com': '哒哒影视',
        'netflix.com': 'Netflix',
        'hulu.com': 'Hulu',
        'disney.com': 'Disney+',
        'primevideo.com': 'Prime Video',
        'hbo.com': 'HBO Max',
        'crunchyroll.com': 'Crunchyroll',
        'funimation.com': 'Funimation',
        'youtube.com': 'YouTube',
        'bilibili.com': '哔哩哔哩',
        'youku.com': '优酷',
        'iqiyi.com': '爱奇艺',
        'qq.com': '腾讯视频',
        'mgtv.com': '芒果TV'
    };

    // 移除www前缀
    const cleanHostname = hostname.replace('www.', '');

    // 查找预定义的名称
    if (nameMap[cleanHostname]) {
        return nameMap[cleanHostname];
    }

    // 从域名生成名称
    let name = cleanHostname.split('.')[0];
    name = name.charAt(0).toUpperCase() + name.slice(1);

    return name;
};

// 生成搜索URL的函数
const generateSearchUrl = (baseUrl) => {
    try {
        const urlObj = new URL(baseUrl);
        const hostname = urlObj.hostname.toLowerCase();

        // 根据不同网站生成对应的搜索URL模式
        const searchPatterns = {
            // 影视相关网站
            'douban.com': '/subject_search?search_text={keyword}',
            'imdb.com': '/find?q={keyword}',
            'subaibai.com': '/search?q={keyword}',
            'libvio.site': '/search/-------------.html?wd={keyword}&submit=',
            'ddys.pro': '/?s={keyword}&post_type=post',
            'gimy.ai': '/search/-------------.html?wd={keyword}',
            'anime1.me': '/?s={keyword}',
            'dddym.com': '/search?s={keyword}&p=1',
            'netflix.com': '/search?q={keyword}',
            'hulu.com': '/search?q={keyword}',
            'disney.com': '/search?q={keyword}',
            'primevideo.com': '/search?phrase={keyword}',
            'hbo.com': '/search?q={keyword}',
            'crunchyroll.com': '/search?q={keyword}',
            'funimation.com': '/search?q={keyword}',
            // 视频平台
            'youtube.com': '/results?search_query={keyword}',
            'bilibili.com': '/search?keyword={keyword}',
            'youku.com': '/search_show/q_{keyword}',
            'iqiyi.com': '/search/{keyword}',
            'qq.com': '/search.html?query={keyword}',
            'mgtv.com': '/search?keyword={keyword}',
            // 通用搜索
            'baidu.com': '/s?wd={keyword}',
            'google.com': '/search?q={keyword}',
            'bing.com': '/search?q={keyword}',
            'zhihu.com': '/search?q={keyword}',
            'weibo.com': '/search?q={keyword}'
        };

        // 查找匹配的搜索模式
        for (const [domain, pattern] of Object.entries(searchPatterns)) {
            if (hostname.includes(domain)) {
                return `${urlObj.protocol}//${urlObj.host}${pattern}`;
            }
        }

        // 通用搜索模式尝试
        const commonSearchPaths = [
            '/search?q={keyword}',
            '/search?keyword={keyword}',
            '/search?s={keyword}',
            '/search.php?q={keyword}',
            '/search.html?q={keyword}',
            '/?s={keyword}',
            '/find?q={keyword}'
        ];

        // 默认使用第一个通用模式
        return `${urlObj.protocol}//${urlObj.host}${commonSearchPaths[0]}`;
    } catch (error) {
        console.error('生成搜索URL失败:', error);
        return `${baseUrl}/search?q={keyword}`;
    }
};

// 批量导入网站信息
export const importMultipleWebsites = async (urls) => {
    const results = [];
    const errors = [];

    for (const url of urls) {
        try {
            const websiteInfo = await fetchWebsiteInfo(url.trim());
            results.push(websiteInfo);
        } catch (error) {
            errors.push({ url: url.trim(), error: error.message });
        }
    }

    return { results, errors };
};

// 简化版本的网站信息获取（不依赖外部API）
export const getBasicWebsiteInfo = (url) => {
    try {
        const normalizedUrl = url.startsWith('http') ? url : `https://${url}`;
        const urlObj = new URL(normalizedUrl);

        // 从域名生成网站名称
        let name = generateWebsiteName(urlObj.hostname);

        // 生成图标URL
        const icon = `${urlObj.protocol}//${urlObj.host}/favicon.ico`;

        // 生成搜索URL
        const searchUrl = generateSearchUrl(normalizedUrl);

        return {
            name: name,
            url: normalizedUrl,
            icon: icon,
            searchUrl: searchUrl,
            disabled: false
        };
    } catch (error) {
        console.error('解析URL失败:', error);
        throw new Error('无效的URL格式');
    }
};